package com.zxb.rocketmq.springboot_rocketmq_demo.controller;

import com.zxb.rocketmq.springboot_rocketmq_demo.entity.MsgTest;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 * 顺序消息
 * @author shangtf
 */
@RestController
@RequestMapping("/orderMq")
@Slf4j
public class OrderProducerController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate; //注入Mq



    /**
     * 顺序消息
     * 使用rocketmq-spring-boot-starter发送顺序消息就比较方便了，不像使用rocket-client那样，
     * 需要手动获取RocketMQ中当前topic的队列个数然后再通过hashKey值，mqs.size()取模，得到一个索引值，这里底层都帮我们做好了处理！
     * */
    @RequestMapping("/orderStr1")
    public void sendOrderStr()  {

        List<MsgTest> msgList = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            msgList.add(new MsgTest(100, "我是id为100的第" + (i + 1) + "条消息", new Date()));
        }
        msgList.forEach(t -> {
            rocketMQTemplate.asyncSendOrderly("first-topic-str:tag1", t, String.valueOf(t.getId()), new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    log.info("异步消息发送成功:{}", sendResult);
                }
                @Override
                public void onException(Throwable throwable) {
                    log.info("异步消息发送失败:{}", throwable.getMessage());
                }
            });
        });

    }
}
